package com.mvvm.start.common.utils

import android.annotation.SuppressLint
import android.app.Notification
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.view.WindowManager
import androidx.core.app.NotificationCompat
import androidx.core.content.FileProvider
import com.mvvm.start.base.BaseApplication
import com.mvvm.start.base.utils.loge
import com.mvvm.start.base.utils.toast
import com.mvvm.start.common.R
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.launch
import java.io.File

/**
 * @author lmy
 * @功能: 下载自动更新App帮助类
 * @Creat 2/24/21 10:38 AM
 * @Compony 465008238@qq.com
 */

@SuppressLint("StaticFieldLeak")
object UpDateAppHelper {
    private var context = BaseApplication.context
    private var isdownloading = false

    //下载通知进度提示
    private var notificationManager = BaseApplication.application.notificationManager
    private lateinit var notification: Notification
    private var builder = BaseApplication.application.notificationBuilder
    val windowTYPE = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY
    } else {
        WindowManager.LayoutParams.TYPE_PHONE
    }

    //这里禁用了通知栏进度提示 会影响下载进度
    private var isShowNotification = false
    fun updateApp(
        url: String,
        isAutomatic: Boolean,
        fileName: String,
        progress: (progress: Int) -> Unit,
        success: () -> Unit,
        error: (error: String) -> Unit
    ) {
        if (isdownloading) {
            "正在下载中".toast()
            return
        }
        "开始下载".toast()
     DownloadUtils.downloadFile(url, fileName,
            {
                "开始下载${Thread.currentThread().name}".loge("UpDateAppHelper")

                if (isShowNotification) {
                    initNotification()
                }
                isdownloading = true
            }, {
                progress(it)
//                "下载进度:$it%".loge("UpDateAppHelper")
                "下载进度进程${Thread.currentThread().name}".loge()
                if (isShowNotification) {
                    notification = builder
                        .setProgress(100, it, false)
                        .setContentText("下载进度:$it%")
                        .build()
                    notificationManager.notify(1, notification)
                }
                isdownloading = true
            }, {
                success()
//                dataProgressDialog.dismiss()
                isdownloading = false
//                "完成下载".loge("UpDateAppHelper")
                if (isAutomatic) {
                    installAPK(context, File(it))
                    if (isShowNotification) {
                        notificationManager.cancel(1)
                    }
                } else {
                    if (isShowNotification) {
                        val intent = Intent(Intent.ACTION_VIEW).apply {
                            flags = Intent.FLAG_ACTIVITY_NEW_TASK
                            //添加这一句表示对目标应用临时授权该Uri所代表的文件
                            addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
                            // 由于没有在Activity环境下启动Activity,设置下面的标签
                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                                // 版本大于 N ，开始使用 fileProvider 进行安装
                                val apkUri = FileProvider.getUriForFile(
                                    context!!,
                                    "com.mvvm.start.fileprovider",
                                    File(it)
                                )
                                setDataAndType(apkUri, "application/vnd.android.package-archive")
                            } else {
                                // 正常进行安装
                                setDataAndType(
                                    Uri.fromFile(File(it)),
                                    "application/vnd.android.package-archive"
                                )
                            }
                        }
                        val pi = PendingIntent.getActivity(context, 0, intent, 0)
                        notification = builder.setContentTitle("下载完成")
                            .setContentText("点击安装")
                            .setAutoCancel(true) //设置通知被点击一次是否自动取消
                            .setContentIntent(pi)
                            .build()
                        notificationManager.notify(1, notification)
                    }

                }
            }, {
                MainScope().launch(Dispatchers.Main) {
                    error(it)
                    isdownloading = false
                    if (isShowNotification) {
                        notification = builder.setContentTitle("下载失败")
                            .setContentText(it)
                            .setAutoCancel(true) //设置通知被点击一次是否自动取消
                            .build()
                        notificationManager.notify(1, notification)
                    }
                }
            })
    }

    //初始化通知
    private fun initNotification() {
        builder.apply {
            setContentTitle("正在更新...") //设置通知标题
            setSmallIcon(R.mipmap.ic_launcher)
//            .setLargeIcon(
//                BitmapFactory.decodeResource(
//                    this.resources,
//                    R.mipmap.ic_launcher
//                )
//            ) //设置通知的大图标
            priority = NotificationCompat.PRIORITY_MAX //设置通知的优先级：最大
            setAutoCancel(false) //设置通知被点击一次是否自动取消
            setContentText("下载进度: 0%")
            setDefaults(NotificationCompat.FLAG_ONLY_ALERT_ONCE)
            setOnlyAlertOnce(true)//设置为true  声音只提示一次
            setProgress(100, 0, false)
        }
        notification = builder.build() //构建通知对象
        notificationManager.notify(1, notification)
    }

    fun installAPK(activity: Context, filePath: File?) {
        val apkUri = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            // 版本大于 N ，开始使用 fileProvider 进行安装
            FileProvider.getUriForFile(context, "com.mvvm.start.fileprovider", filePath!!)
        } else {
            Uri.fromFile(filePath)
        }
        val intent = Intent(Intent.ACTION_VIEW).apply {
            flags = Intent.FLAG_ACTIVITY_NEW_TASK
            //添加这一句表示对目标应用临时授权该Uri所代表的文件
            addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
            setDataAndType(apkUri, "application/vnd.android.package-archive")
        }
        activity.startActivity(intent)
    }
}